package org.xiaojl.xcloud.tools.gateway.filter.post;

import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.xiaojl.xcloud.tools.gateway.RpcResult;
import org.xiaojl.xcloud.tools.gateway.kit.FilterKit;
import org.xiaojl.xcloud.tools.gateway.kit.JsonKit;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**  
 * <p>Title: AccessLogPostFilter</p>  
 *
 * <p>Description: 访问日志过滤器</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月17日  
 */
@Component
public class AccessLogPostFilter extends ZuulFilter {
	
	@Override
	public boolean shouldFilter() {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();
		String uri = request.getRequestURI();
		return !"/xcloudError".equals(uri) && FilterKit.isFilterFlag(context);
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		String result = "";
		try {
			//获取服务响应结果
			InputStream inputStream = context.getResponseDataStream();
			result = StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
			
		} catch (Exception e) {
			result = JsonKit.toJson(RpcResult.fail("服务繁忙,请稍后再试", e.getLocalizedMessage()));
		}finally{
			//写入响应
			FilterKit.setRespBody(context, result);
		}
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.POST_TYPE;
	}

	@Override
	public int filterOrder() {
		return 100;
	}

}
